<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>jQuery</title>
    <script src="./js/sizzle.min.js"></script>
</head>
<body>
            <h1>Hello world!</h1>
            <h1>Hello world!</h1>
            <h1>Hello world!</h1>
    <script>
        function jQuery (selector) {
            return new jQuery.fn.init(selector);
        }
        jQuery.fn = jQuery.prototype;
        //在原型上添加函数来充当构造函数
        jQuery.prototype.init = function (selector) {
            console.log(selector);
            //如果是 DOM 对象，不需要获取 DOM 对象
            if(typeof(selector) == 'object') {
                //向this中添加DOM
                [].push.call(this, selector);
            } else if(typeof(selector) == 'string') {
                Sizzle(selector, document, this);
            }
            return this;
        }

        //两者都是对象，给fu添加方法等同于给左边添加方法
        jQuery.prototype.init.prototype = jQuery.fn;
        jQuery.fn.on = function(type, cb) {
            console.log(this);
            //为谁添加事件?

            //将 this 这个伪数组转成真数组，nodes 是纯DOM
            var nodes = Array.from(this);
            console.log(nodes);
            nodes.forEach(element => {
                element.addEventListener(type, function(){
                    console.log('你点击了xx');
                    //改变回调函数指向当前 DOM
                    cb.call(this);
                })
            });
        }

        jQuery.fn.css = function(attr, val){
            // console.log(this);
            var nodes = Array.from(this);
            nodes.forEach(function(v) {
                v.style[attr] = val;
            });
        }

        var $ = jQuery;

        $('h1').on('click', function() {
            // console.log($(this));
            $(this).css('color', 'red');
        });

        // $('h1').css('color', 'red');

    </script>
</body>
</html>